//
//  ShopViewController.m
//  BabyAndBaby
//
//  Created by 范琦 on 16/7/27.
//  Copyright © 2016年 范琦. All rights reserved.
//


/*
 先进行片区请求 拿到片区个数和ID之后 根据个数先创建table  创建table的同时 创建两个字典 分别存放数据和table  key值都是对应的片区ID   tableDic的value是对应的tableView   allDic的value是对应的数据  当我需要的时候 遍历tableDic 找到对应的table 反向就拿到了片区ID  同时可以通过片区ID从另一个数据字典中取到对应的数据
 */

#import "ShopViewController.h"
#import "LyScrollMenu.h"
#import "ShopViewCell.h"
#import "ShopSearchViewController.h"
#import "ShopModel.h"
#import "PQModel.h"
#import "ShopDetailViewController.h"


@interface ShopViewController ()<UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate>
@property (nonatomic, strong) LyScrollMenu *scroll;
@property (nonatomic, strong) NSMutableArray *viewArr;      //滚动view数组
@property (nonatomic, strong) NSMutableArray *listArr;   //数据源
@property (nonatomic, strong) NSMutableDictionary *allDic;   //数据源字典 key为片区ID value为数据源数组
@property (nonatomic, strong) NSMutableDictionary *tableDic;   //table字典 目的是将片区和table对应上 key为片区ID value为table

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *pqArr;   //片区数组
@property (nonatomic, strong) NSMutableArray *pqTitleArr;   //片区数组


@end

@implementation ShopViewController

- (void)loadView {
    [super loadView];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.tabBarController.tabBar.hidden = NO;

    
    return;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];

    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.translucent=NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    _viewArr = [NSMutableArray array];
    _allDic = [NSMutableDictionary dictionary];
    _tableDic = [NSMutableDictionary dictionary];

    [self creatRightItem];
    self.listArr = [NSMutableArray array];

    [self netHandlePQ];
    
}

- (void)creatRightItem
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        ShopSearchViewController *searchVC = [[ShopSearchViewController alloc]init];
        [self.navigationController pushViewController:searchVC animated:YES];
        self.navigationController.navigationBarHidden = NO;
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];


}
#warning 网络请求

//参数str是片区ID
- (void)netHandle:(NSString *)str
{
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"/Merchant/merchantList.html" paramDic:@{@"token" : TOKEN,@"area_id":str} RegisterApiMethod:RequestMethodGet];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSArray *arr = request.responseBody[@"result"][@"data"];
        
        
        NSMutableArray *listArr = [NSMutableArray array];
        listArr = _allDic[str];
        listArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            ShopModel *model = [[ShopModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            
            [listArr addObject:model];
        }
        [_allDic setObject:listArr forKey:str];
        UITableView *table = _tableDic[str];
        [table reloadData];
        // 124 352 75 36

        
        
    } failure:^(YTKBaseRequest *request) {
        
    } ];
}
#warning 片区的请求
- (void)netHandlePQ
{
    _pqArr = [NSMutableArray array];
    _pqTitleArr = [NSMutableArray array];
    
    NSString *str = TOKEN;
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:@"/Merchant/getMerchantArea.html" paramDic:@{@"token" : TOKEN} RegisterApiMethod:RequestMethodGet];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSArray *arr = request.responseBody[@"result"];
        for (NSDictionary *dic in arr) {
            PQModel *model = [[PQModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_pqArr addObject:model];
            [_pqTitleArr addObject:model.name];
        }
        if (_viewArr.count == 0 || _viewArr.count != _pqTitleArr.count) {
            
            [self creatTableView];
            [self creatMenuScroll];
        }
        
        
        for (int i = 0; i < _pqArr.count; i++) {
            PQModel *pq = _pqArr[i];
            [self netHandle:[pq.area_id stringValue]];

        }
     
        
    } failure:^(YTKBaseRequest *request) {
        
    } ];
}



- (void)creatTableView
{
    if (_viewArr.count != 0) {
        for (UITableView *tableView in _viewArr) {
            [tableView reloadData];
        }
        
        
    }else{
    
        for (int i = 0; i < _pqArr.count; i++) {
            
            UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, _scroll.bounds.size.height) style:UITableViewStylePlain];
            
            [tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
            //        [tableView headerBeginRefreshing];
            
            [_scroll addSubview:tableView];
            tableView.delegate = self;
            tableView.tag = 2000 + i;
            tableView.dataSource = self;
            tableView.backgroundColor = HUIBACKGROUNDCOLOR;
            [tableView registerNib:[UINib nibWithNibName:@"ShopViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
            tableView.rowHeight = 107;
            [_viewArr addObject:tableView];
            tableView.sectionFooterHeight = 0;
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            tableView.tag = i + 1000;
            tableView.showsVerticalScrollIndicator = NO;
            // 将片区ID作为key  新创建数组和table作为value 分开存在两个字典内
            PQModel *model = _pqArr[i];
            [_allDic setObject:[NSMutableArray array] forKey:[model.area_id stringValue]];
            [_tableDic setObject:tableView forKey:[model.area_id stringValue]];
            
        }
    }
    
    
}

- (void)creatMenuScroll
{
    
    
    
    
    self.scroll = [[LyScrollMenu alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT - 60) ControllerViewArray:_viewArr TitleArray:_pqTitleArr MaxShowTitleNum:5];
    
    
    [self.view addSubview:_scroll];
    
    
}
- (void)setupRefresh
{
    //下拉刷新
    //    [self headerRereshing];

    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
//    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
}
//下拉刷新
#warning 下拉刷新
- (void)headerRereshing
{
//    [self.listArr removeAllObjects];
//    self.allDic = [NSMutableDictionary dictionary];
//    self.tableDic = [NSMutableDictionary dictionary];
    [self netHandlePQ];
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //2.结束刷新
        for (UITableView *table in _viewArr) {
            [table reloadData];
            [table headerEndRefreshing];
        }
//        [_tableView reloadData];
//        [self.tableView headerEndRefreshing];
    });
}
#warning TableView代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSArray *arr = [_tableDic allKeys];
    for (int i = 0; i < arr.count; i++) {
        UITableView *table = _tableDic[arr[i]];
        if (tableView == table) {
            NSArray *listArr = _allDic[arr[i]];
            return listArr.count;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 14;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 20)];
    view.backgroundColor = HUIBACKGROUNDCOLOR;
    return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    
    NSArray *arr = [_tableDic allKeys];
    for (int i = 0; i < arr.count; i++) {
        UITableView *table = _tableDic[arr[i]];
        if (tableView == table) {
            NSArray *listArr = _allDic[arr[i]];
            ShopModel *shop = listArr[indexPath.section];
            cell.shopModel = shop;
            [[cell.phoneBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",[shop.user_name stringValue]];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }];
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray *arr = [_tableDic allKeys];
    for (int i = 0; i < arr.count; i++) {
        UITableView *table = _tableDic[arr[i]];
        if (tableView == table) {
            NSArray *listArr = _allDic[arr[i]];
            ShopModel *shop = listArr[indexPath.section];
            
            
            
            ShopDetailViewController *detail = [[ShopDetailViewController alloc]init];
            detail.str = [shop.myId stringValue];
            [self.navigationController pushViewController:detail animated:YES];
        }
    }


}
#warning webView代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"开始");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"结束");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
    NSLog(@"错误%@", error);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
